"""
OpenGauss 数据库内省模块 - 修复与 Django 5.x 的兼容性问题
"""
from django.db.backends.postgresql.introspection import DatabaseIntrospection as PostgreSQLIntrospection


class DatabaseIntrospection(PostgreSQLIntrospection):
    """
    OpenGauss 数据库内省，基于 PostgreSQL 但处理差异
    """

    def get_table_list(self, cursor):
        """
        获取数据库中的表列表，兼容 OpenGauss
        """
        # OpenGauss 不支持 relispartition 字段，使用简化版本的查询
        cursor.execute("""
            SELECT c.relname, 
                   CASE WHEN c.relkind = 'r' THEN 't'
                        WHEN c.relkind = 'v' THEN 'v'
                        ELSE 'o'
                   END as type
            FROM pg_class c
            LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
            WHERE c.relkind IN ('r', 'v')
                AND n.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                AND pg_table_is_visible(c.oid)
            ORDER BY c.relname
        """)
        
        from django.db.backends.base.introspection import TableInfo
        return [TableInfo(row[0], row[1]) for row in cursor.fetchall()]

    def get_constraints(self, cursor, table_name):
        """
        获取表约束信息，兼容 OpenGauss SQL 语法
        """
        # OpenGauss 不支持 WITH ORDINALITY 语法，使用兼容的替代方案
        cursor.execute("""
            SELECT
                c.conname,
                array_agg(a.attname ORDER BY a.attnum) AS columns,
                c.contype,
                NULL AS foreign_table,
                NULL AS foreign_columns,
                c.consrc,
                c.condeferrable,
                c.condeferred
            FROM pg_constraint c
            JOIN pg_class t ON c.conrelid = t.oid
            JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(c.conkey)
            WHERE t.relname = %s
            GROUP BY c.conname, c.contype, c.consrc, c.condeferrable, c.condeferred
        """, [table_name])
        
        constraints = {}
        for constraint, columns, kind, f_table, f_columns, definition, deferrable, deferred in cursor.fetchall():
            constraints[constraint] = {
                'columns': list(columns) if columns else [],
                'primary_key': kind == 'p',
                'unique': kind in ['p', 'u'],
                'foreign_key': f_table if kind == 'f' else None,
                'check': kind == 'c',
                'index': False,
                'definition': definition,
                'options': {},
            }
        
        # 获取索引信息
        cursor.execute("""
            SELECT
                i.relname AS index_name,
                array_agg(a.attname ORDER BY a.attnum) AS columns,
                ix.indisunique,
                ix.indisprimary
            FROM pg_index ix
            JOIN pg_class i ON i.oid = ix.indexrelid
            JOIN pg_class t ON t.oid = ix.indrelid
            JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)
            WHERE t.relname = %s
            GROUP BY i.relname, ix.indisunique, ix.indisprimary
        """, [table_name])
        
        for index, columns, unique, primary in cursor.fetchall():
            if index not in constraints:
                constraints[index] = {
                    'columns': list(columns) if columns else [],
                    'primary_key': primary,
                    'unique': unique,
                    'foreign_key': None,
                    'check': False,
                    'index': True,
                    'definition': None,
                    'options': {},
                }
        
        return constraints